package com.hefan.club.comment.service;

import com.alibaba.fastjson.JSON;
import com.cat.common.entity.Page;
import com.google.common.collect.Maps;
import com.hefan.club.comment.bean.Comments;
import com.hefan.club.comment.bean.ParentCommentsVo;
import com.hefan.club.comment.dao.CommentsDao;
import com.hefan.club.comment.itf.CommentsService;
import com.hefan.club.dynamic.bean.Message;
import com.hefan.club.dynamic.dao.DynamicDao;
import com.hefan.club.dynamic.itf.DynamicService;
import com.hefan.club.dynamic.itf.cache.RedisDynamicService;
import com.hefan.notify.itf.MessageService;
import com.hefan.oms.bean.Present;
import com.hefan.oms.bean.RebalanceVo;
import com.hefan.oms.itf.CommentReBalanceService;
import com.hefan.oms.itf.PresentService;
import com.hefan.user.bean.WebUser;
import com.hefan.user.itf.WebUserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

@Component("commentsService")
public class CommentsServiceImpl implements CommentsService {

	@Resource
	private CommentsDao commentsDao;
	@Resource
	private MessageService messageService;
	@Resource
	private CommentReBalanceService commentReBalanceService;
	@Resource
	private DynamicService dynamicService;
	@Resource
	private PresentService presentService;
	@Resource
	WebUserService webUserService;
	@Resource
	private RedisDynamicService redisDynamicService;
	@Resource
	private DynamicDao dynamicDao;


	private Logger logger = LoggerFactory.getLogger(CommentsServiceImpl.class);

	@Override
	public Comments getCommentsByIdForCheck(long commentsId){
		try {
			return this.commentsDao.getCommentsByIdForCheck(commentsId);
		}catch (Exception e){
			logger.error("查询评论异常{}",e);
			return null;
		}
	}

	@Override
	public Page<Map<String, Object>> getComments(int messageId, String userId, int isPresent, Page<Map<String, Object>> page) {
		Page<Map<String, Object>> pageList = new Page<>();
		try {

			pageList = commentsDao.getComment(messageId, userId, isPresent, page);
			if (pageList.getTotalItems() > 0) {
				List<Map<String, Object>> list = pageList.getResult();
				if (!CollectionUtils.isEmpty(list)) {
					for (Map<String, Object> map : list) {
						WebUser user = webUserService.getWebUserInfoByUserId(map.get("user_id").toString());

						//当前用户是否为有效用户
						if (user == null) {
							logger.info("用户不是有效用户userId={}", userId);
							 break;
						}
						logger.info("CommentsServiceImpl getComments 用户信息{}", JSON.toJSONString(user));
						map.put("head_img", user.getHeadImg());
						SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						map.put("comments_time", sdf.format(sdf.parse(map.get("comments_time").toString())));
						map.put("nick_name", user.getNickName());
						map.put("user_type", user.getUserType());
						map.put("sex", user.getSex());
						map.put("user_level", user.getUserLevel());
						map.put("present_name", "");
						map.put("present_icon", "");

						if (map.get("present_id") != null) {
							Present present = presentService.getPresentInfoById(Long.parseLong(map.get("present_id").toString()));
							if (present != null) {
								map.put("present_name", present.getPresentName());
								map.put("present_icon", present.getIcon());
							}
						}
						//主播用户
						WebUser anchtor = webUserService.getWebUserInfoByUserId(String.valueOf(map.get("muser_id")));
						map.put("ancNickName", anchtor.getNickName());
					}

				}
			}
		} catch (Exception e) {
			logger.error("获取评论异常{}", e);
		}
		return pageList;
	}

	@Override
	public Map<Integer, ParentCommentsVo> getParentCommentsByIds(List<Integer> ids) {
		Map<Integer, ParentCommentsVo> resMap = Maps.newHashMap();
		try {
			List<Map<String, Object>> list = commentsDao.getParentCommentsByIds(ids);

			if (!CollectionUtils.isEmpty(list)) {
				for (Map<String, Object> map : list) {
					if (CollectionUtils.isEmpty(map)) {
						continue;
					}
					ParentCommentsVo pcom = new ParentCommentsVo();
					if (map.containsKey("id")) {
						pcom.parentCommentsId = (map.get("id") == null ? 0 : Integer.parseInt(map.get("id").toString()));
					}
					WebUser user = webUserService.getWebUserInfoByUserId(String.valueOf(map.get("user_id")));
					if (user == null) {
						continue;
					}
					String time = map.get("comments_time").toString();
					SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					map.put("comments_time",sdf.format(sdf.parse(time)));
					pcom.parentUserId = user.getUserId();
					pcom.parentHeadImg = user.getHeadImg();
					pcom.parentNickName = user.getNickName();
					pcom.parentUserType = user.getUserType();
					pcom.parentSex = user.getSex();
					pcom.parentLevel = String.valueOf(user.getUserLevel());
					if (map.containsKey("comments_info")) {
						pcom.parentCommentsInfo = (map.get("comments_info") == null ? "" : map.get("comments_info").toString());
					}

					if (map.containsKey("comments_infostatus")) {
						pcom.parentStatus = 0;
						if (map.get("comments_infostatus") != null) {
							if (!map.get("comments_infostatus").toString().equals("1")) {
								pcom.parentStatus = 1;
							}
						}
					}
					Present present = presentService.getPresentInfoById(Long.parseLong(map.get("present_id").toString()));
					if (present == null) {
						present = new Present();
					}
					// 礼物id(为0不是礼物评论)
					pcom.parentPresentId = present.getId().intValue();

					pcom.parentPresentName = present.getPresentName();
					pcom.parentPresentIcon = present.getIcon();
					pcom.parentCommentsTime = map.get("comments_time") == null ? "" : map.get("comments_time").toString();
					resMap.put(pcom.parentCommentsId, pcom);
				}
			}
		}catch (Exception e){
			logger.error("根据父id获取评论/回复的父消息异常{}", e);
		}
		return resMap;
	}



	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public int saveCommentsInfo(Comments com) {
		try {
			int uc = this.commentsDao.saveCommentsInfo(com);
			String userId = com.getParentUserId();
			if (StringUtils.isBlank(com.getParentUserId())) {
				userId = com.getMuserId();
			}
			if (uc > 0) {
				// 判断礼物
				if (com.getPresentId() != null && com.getPresentId() > 0) {
					RebalanceVo vo = new RebalanceVo();
					vo.setFromId(com.getUserId());
					vo.setToId(com.getMuserId());
					vo.setMessageId(com.getMessageId());
					vo.setPresentId(com.getPresentId());
					vo.setPresentNum(1);
					vo.setLiveUuid("club");
					// 扣费 //明星收入
					try {
						commentReBalanceService.reBalance(vo);
					} catch (Exception e) {
						// 扣费失败主动抛出异常
						e.printStackTrace();
						throw new RuntimeException("礼物扣费失败");
					}

					try {
						// 修改通知消息数
						this.messageService.addMsgCout(5, userId);
						// 增加礼物数
						this.dynamicService.addMessageCount(com.getMessageId().toString(), userId, "2");
					} catch (Exception e) {
						e.printStackTrace();
					}
				} else {
					try {
						// 修改通知消息数
						this.messageService.addMsgCout(3, userId);
						// 增加评论数
						this.dynamicService.addMessageCount(com.getMessageId().toString(), userId, "1");
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
			return uc;
		} catch (Exception e) {
			logger.error("新增评论/回复/礼物评论异常{}", e);
			return 0;
		}

	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public int deleteCommentsById(long commentsId, int messageId, boolean isPresent,String userId) {
		try {
			int uc = this.commentsDao.deleteCommentsById(commentsId);
			Message message = dynamicService.getCacheMessageInfo(String.valueOf(messageId),userId);
			if(message ==null ){
				return 0;
			}
			if (uc > 0) {
				try {
					// 获取评论是否有子评论
					int subSetCount = this.commentsDao.getCommentsSubSet(commentsId);
					// 没有子评论评论数-1
					if (subSetCount <= 0) {
						this.dynamicService.reMessageCount(messageId + "", message.getUserId(), isPresent ? "2" : "1");
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			return uc;
		} catch (Exception e) {
			logger.error("删除品论/回复异常{}", e);
			return 0;
		}
	}

	@Override
	public Map getCommentsFristByUserId(String userId, int isPresent) {
		Map<String, Object> map = Maps.newHashMap();
		try {
			if (isPresent == 1) {
				map = commentsDao.getFristGiftCommentByUserId(userId);
			} else {
				map = this.commentsDao.getFristCommentByUserId(userId);
			}
			if (CollectionUtils.isEmpty(map) || !map.containsKey("time")) {
				return null;
			}
			String time = String.valueOf(map.get("time"));
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			map.put("time",sdf.format(sdf.parse(time)));
			Present present =null;
			if (isPresent == 1 && map.containsKey("present_id")) {
				present = presentService.getPresentInfoById(Long.parseLong(String.valueOf(map.get("present_id"))));
			}
			map.put("present_name", "");
			map.put("present_icon", "");
			map.put("comment_persion", "");
			if (present != null) {
				map.put("present_name", present.getPresentName());
				map.put("present_icon", present.getIcon());
			}
			WebUser user = webUserService.getWebUserInfoByUserId(userId);
			if (user == null) {
				map.put("comment_persion", user.getNickName());
			}

		} catch (Exception e) {
			logger.error("获取第一条数据userId=={},isPresent={}异常{}",userId,isPresent, e);
		}
		return map;
	}
}
